import axios from 'axios'
import type { LoginRequest, RegisterRequest, JwtResponse, User } from '../types/user'

const API_URL = '/api/auth/'
const USER_API_URL = '/api/users'

// 创建axios实例
const authAxios = axios.create()

// 请求拦截器，添加token
authAxios.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 认证服务
class AuthService {
  // 登录
  async login(credentials: LoginRequest): Promise<JwtResponse> {
    const response = await axios.post<JwtResponse>(API_URL + 'signin', credentials)
    if (response.data.token) {
      localStorage.setItem('token', response.data.token)
      localStorage.setItem('userInfo', JSON.stringify({
        id: response.data.id,
        username: response.data.username,
        email: response.data.email,
        roles: response.data.roles
      }))
    }
    return response.data
  }

  // 注册
  async register(user: RegisterRequest): Promise<any> {
    return axios.post(API_URL + 'signup', user)
  }

  // 登出
  logout(): void {
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  // 获取当前用户信息
  getCurrentUser(): any {
    const userInfo = localStorage.getItem('userInfo')
    return userInfo ? JSON.parse(userInfo) : null
  }

  // 获取所有用户（管理员权限）
  async getAllUsers(): Promise<User[]> {
    const response = await authAxios.get<User[]>(USER_API_URL)
    return response.data
  }

  // 获取单个用户（管理员权限）
  async getUserById(id: number): Promise<User> {
    const response = await authAxios.get<User>(USER_API_URL + id)
    return response.data
  }

  // 更新用户（管理员权限）
  async updateUser(id: number, user: User): Promise<User> {
    const response = await authAxios.put<User>(USER_API_URL + id, user)
    return response.data
  }

  // 删除用户（管理员权限）
  async deleteUser(id: number): Promise<void> {
    await authAxios.delete(USER_API_URL + id)
  }

  // 导出用户列表到Excel
  async exportUsersToExcel(searchQuery?: string, roleFilter?: string): Promise<Blob> {
    const params = new URLSearchParams();
    if (searchQuery) {
      params.append('searchQuery', searchQuery);
    }
    if (roleFilter) {
      params.append('roleFilter', roleFilter);
    }
    
    const response = await authAxios.get(USER_API_URL + '/export', {
      params,
      responseType: 'blob'
    });
    
    return response.data;
  }
}

// 检查用户是否已认证
export const isAuthenticated = (): boolean => {
  const token = localStorage.getItem('token')
  return token !== null
}

export default new AuthService()